package org.modelcc.io.java.visitor;

import java.lang.reflect.Field;
import java.util.logging.Level;

import org.modelcc.Value;
import org.modelcc.io.java.JavaModelReader;
import org.modelcc.io.java.JavaLanguageVisitor;
import org.modelcc.io.java.JavaLanguageClass;

/**
 * Java model reader: Class visitor for @Value
 * 
 * @author Fernando Berzal (berzal@acm.org)
 */
public class ValueVisitor extends JavaLanguageVisitor
{	
	private boolean error;
	
	private Field valueField;
	
	public ValueVisitor(JavaModelReader reader)
	{
		super(reader);
	}
	
	@Override
	public void startVisit(Class type, JavaLanguageClass element) 
	{
		error = false;
	}

	@Override
	public void visit(Class type, Field field, JavaLanguageClass element) 
	{
		if (field.isAnnotationPresent(Value.class)) {
			if (valueField == null) {
				valueField = field;
			} else {
				if (!error) {
					log(Level.SEVERE, "In field \"{0}\" of class \"{1}\": The @Value annotation can only be assigned to a single field.", new Object[]{valueField.getName(), type.getCanonicalName()});
					error = true;
				}
				log(Level.SEVERE, "In field \"{0}\" of class \"{1}\": The @Value annotation can only be assigned to a single field.", new Object[]{field.getName(), type.getCanonicalName()});
			}
		}
	}

	@Override
	public void endVisit(Class type, JavaLanguageClass element) 
	{
    	if (error)
    		valueField = null;

    	element.setValueField(valueField);
	}

}
